import { getToken, setToken, delToken } from '@/utils/storage'
import { Login, reqGetUserInfo } from '@/api/user'
const state = {
  token: getToken() || '',
  // 用户信息
  userInfo: {}
}
const mutations = {
  // 登录成功后token存本地
  setToken (state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  // 设置用户信息
  setUser (state, userList) {
    state.userInfo = userList
  },
  clearToken (state) {
    state.token = ''
    delToken()
  },
  clearUserInfo (state) {
    state.userInfo = {}
  }
}
const actions = {
  // 登录请求
  async login (context, obj) {
    const res = await Login(obj)
    // console.log(res)
    context.commit('setToken', res.token)
  },
  async getUserInfo (context) {
    const res = await reqGetUserInfo()
    // console.log(res)
    context.commit('setUser', res.data)
  },
  logout (context) {
    context.commit('clearToken')
    context.commit('clearUserInfo')
  }
}
const getters = {
  // 动态计算文本头像
  textAvatar (state) {
    return state.userInfo.username ? state.userInfo.username.charAt(0).toUpperCase() : ''
  }
}
export default {
  state,
  mutations,
  actions,
  getters,
  namespaced: true
}
